﻿using System;
using System.Configuration;
using System.Web.Routing;
using MvcForum.Net.Utils;
using Nasa8x.Mvc.XmlRouting;

namespace MvcForum.Net
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {


        #region SEO URL Management

        #region 301Redirect Method

        /// <summary>
        /// Redirect old URL to new URL via 301 Header Redirect (SEO Friendly Permanent Redirect)
        /// </summary>
        /// <param name="url"></param>
        private void PermanentRedirect(string url)
        {
            Response.Clear();
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", url);
            Response.End();
        }

        #endregion

        #region MVC Request Cleaner

        /// <summary>
        /// Cleans up passed urls to reduce the number of alternate routes to the same content
        /// Strips postfix slash; etc, as in the comments.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void Application_BeginRequest(Object sender, EventArgs e)
        //{
        //    #region Rewriting IIS6 Fix 27112009

        //    var app = sender as HttpApplication;
        //    if (app != null)
        //        if (app.Request.AppRelativeCurrentExecutionFilePath == "~/rewritten.aspx")
        //            app.Context.RewritePath(
        //                app.Request.Url.PathAndQuery.Replace("/rewritten.aspx", "")
        //                );

        //    #endregion Rewriting IIS6 Fix

        //    // Get the requested URL so we can do some validation on it.
        //    // We exclude the query string, and add that later, so it's not included
        //    // in the validation
        //    string url = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority +
        //                  HttpContext.Current.Request.Url.AbsolutePath);

        //    // If we're not a request for the root, and end with a slash, strip it off
        //    if (HttpContext.Current.Request.Url.AbsolutePath != "/" &&
        //        HttpContext.Current.Request.Url.AbsolutePath.EndsWith("/"))
        //        PermanentRedirect(url.Substring(0, url.Length - 1) + HttpContext.Current.Request.Url.Query);

        //    // If we end with /1 we're a page 1, and don't need (shouldn't have) the page number
        //    if (HttpContext.Current.Request.Url.AbsolutePath.EndsWith("/1"))
        //        PermanentRedirect(url.Substring(0, url.Length - 2) + HttpContext.Current.Request.Url.Query);

        //    // If we have double-slashes, strip them out
        //    else if (HttpContext.Current.Request.Url.AbsolutePath.Contains("//"))

        //        PermanentRedirect(url.Replace("//", "/") + HttpContext.Current.Request.Url.Query);

        //    // If we've got uppercase characters, fix
        //    else if (Regex.IsMatch(url, @"[A-Z]"))
        //        PermanentRedirect(url.ToLower() + HttpContext.Current.Request.Url.Query);
        //}

        #endregion

        #endregion SEO URL Management


        //public MvcApplication()
        //{
        //    BeginRequest += delegate
        //    {

        //    };
        //    //EndRequest += delegate
        //    //{
        //    //    if (CurrentSession != null)
        //    //        CurrentSession.Dispose();
        //    //};

        //}

        //public static void OnBeginRequest()
        //{


        //}




        protected void Session_End(Object sender, EventArgs e)
        {
           bool login= ForumContext.Logined;

        }


        //protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
        //{

        //    // only apply session cookie persistence to requests requiring session information



        //    #region session cookie

        //    if (Context.Handler is IRequiresSessionState)
        //    {

        //        // Ensure ASP.NET Session Cookies are accessible throughout the subdomains.



        //        if (Request.Cookies["ASP.NET_SessionId"] != null && Session.SessionID != null)
        //        {

        //            Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;

        //            Response.Cookies["ASP.NET_SessionId"].Domain = ".know24.net"; // the full stop prefix denotes all sub domains

        //            Response.Cookies["ASP.NET_SessionId"].Path = "/"; //default session cookie path root         

        //        }

        //    }

        //    #endregion

        //}



        public static void RegisterRoutes(RouteCollection routes)
        {
            //      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.IgnoreRoute("scripts/{*pathInfo}");
            //routes.IgnoreRoute("themes/{*pathInfo}");

            ////routes.IgnoreRoute("{*allaspx}", new { allaspx = @".*\.aspx(/.*)?" });
            //routes.IgnoreRoute("{*imagehander}", new { imagehander = @".*\.img.axd(/.*)?" });

            //      routes.Add(new EnableAbsoluteRouting());



            //      routes.MapRoute(
            //             "Forum-Paging",                                              // Route name
            //             "forum-{id}-{page}/{title}",                           // URL with parameters
            //              new { controller = "forum", action = "ShowForum", id = 1, page = UrlParameter.Optional, title = string.Empty }  // Parameter defaults
            //          );


            //      routes.MapRoute(
            //       "Forum",                                              // Route name
            //       "forum-{id}/{title}",                           // URL with parameters
            //        new { controller = "forum", action = "ShowForum", id = 1, title = string.Empty }  // Parameter defaults
            //    );




            //      routes.MapRoute(
            //     "Topics-Paging",                                              // Route name
            //     "thread-{id}-{page}/{title}",                           // URL with parameters
            //      new { controller = "forum", action = "ShowTopic", id = 1, page = UrlParameter.Optional, title = string.Empty }  // Parameter defaults
            //  );



            //      routes.MapRoute(
            //         "Topics",                                              // Route name
            //         "thread-{id}/{title}",                           // URL with parameters
            //          new { controller = "forum", action = "ShowTopic", id = 1, title = string.Empty }  // Parameter defaults
            //      );



            //      routes.MapRoute(
            //        "FindPost",                                              // Route name
            //        "FindPost-{id}",                           // URL with parameters
            //         new { controller = "forum", action = "FindPost", id = UrlParameter.Optional }  // Parameter defaults
            //     );


            //      routes.MapRoute(
            //         "forum-main",                                              // Route name
            //         "forum",                           // URL with parameters
            //         new { controller = "Forum", action = "Index", id = "" }  // Parameter defaults
            //     );





            //      //routes.MapRoute(
            //      //    "Default",                                              // Route name
            //      //    "{controller}/{action}/{id}",                           // URL with parameters
            //      //    new { controller = "Forum", action = "HomePage", id = "" }  // Parameter defaults
            //      //);


            //      routes.MapRoute(
            //          "ControlPanel",                                              // Route name
            //          "CPanel/{action}/{id}",                           // URL with parameters
            //          new { controller = "CPanel", action = "Index", id = "" }  // Parameter defaults
            //      );

            //      routes.MapRoute(
            //        "Member",                                              // Route name
            //        "Member/{action}/{id}",                           // URL with parameters
            //        new { controller = "Member", action = "Index", id = "" }  // Parameter defaults
            //    );

            //      routes.MapRoute(
            //      "Admin",                                              // Route name
            //      "Admin/{action}/{id}",                           // URL with parameters
            //      new { controller = "Admin", action = "Index", id = "" }  // Parameter defaults
            //  );


            //      routes.MapRoute(
            //    "Action",                                              // Route name
            //    "{action}/{page}",                           // URL with parameters
            //    new { controller = "Forum", action = "HomePage", page = UrlParameter.Optional }  // Parameter defaults
            //);




            var section = (MvcRouteConfigurationSection)ConfigurationManager.GetSection("RouteConfiguration");

            routes.MapRoute(section);



        }


        //private static readonly Regex WWW_REGEX = new Regex(@"www\.(?<mainDomain>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {


            const string _prefix = "http://www.";
            string _url = Request.Url.ToString();

            if (_url.StartsWith(_prefix, StringComparison.OrdinalIgnoreCase))
            {
                var _redirectUrl = _url.Replace(_prefix, "http://");

                
                Response.Clear();
                Response.StatusCode = 301;
                Response.StatusDescription = "Moved Permanently";
                Response.AddHeader("Location", _redirectUrl);
                Response.End();


            }

            /*
            string _hostName = Request.Headers["x-forwarded-host"];
            _hostName = string.IsNullOrEmpty(_hostName) ? Request.Url.Host : _hostName;
            Match _match = WWW_REGEX.Match(_hostName);
            if (_match.Success)
            {
                string _mainDomain = _match.Groups["mainDomain"].Value;
                var builder = new UriBuilder(Request.Url)
                {
                    Host = _mainDomain
                };
                string _redirectUrl = builder.Uri.ToString();
                Response.Clear();
                Response.StatusCode = 301;
                Response.StatusDescription = "Moved Permanently";
                Response.AddHeader("Location", _redirectUrl);
                Response.End();
             
            }* */
        }


        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);
        }
    }
}